package Schiffeversenken;


import javax.microedition.media.*;


/**
 *
 * @author Madse
 */
public class BMESound implements Runnable
{
    private Player _player = null;
    private String _file = null;
    private String _type = null;
    private boolean _bmesoundState = false;
    private int _loopCount = 0;

    Thread _t = null;

     /**
     * @param   <String>   file - Datei, wav oder mp3
     * @param   <String>   type - MP3 audio files: audio/mpeg, Wave audio files: audio/x-wav
     */


// Konstruktors Beginn
    public BMESound(String file, String type)
    {
        _file = file;
        _type =  type;
        try {
            _player = Manager.createPlayer(getClass().getResourceAsStream(_file.toString()), _type.toString());
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        _t = new Thread(this);
        _loopCount = 1;

    }


    public BMESound(String file, String type, int lCount)
    {
        _file = file;
        _type =  type;
        try {
            _player = Manager.createPlayer(getClass().getResourceAsStream(_file.toString()), _type.toString());
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        _t = new Thread(this);
        _loopCount = lCount;

    }
// Konstruktors End

    public void start()
    {
        if(!_bmesoundState)
            _t.start();

        _bmesoundState = true;
        run();
    }

    public void stop()
    {
        _bmesoundState = false;
        run();

    }

    public void run()
    {
        if(_bmesoundState)
        {
            playerStart();
        }else
        {
             try
            {
                _player.stop();
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }

    }

    private void playerStart()
    {
        if(_bmesoundState && _player.getState() != _player.STARTED)
        {
            try
            {
                if(_loopCount != 0)
                {
                    _player.setLoopCount(_loopCount);
                }
                _player.start();
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }
// Get Methoden
      public boolean getState()
      {
          return this._bmesoundState;
      }

      public Player getPlayer()
      {
        return _player;
      }
}
